package com.xindacloud.sms.adapter.service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.xindacloud.sms.adapter.entity.SmsUser;
import com.xindacloud.sms.adapter.service.business.ISmsUserService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommonServiceImpl {

    @Autowired
    ISmsUserService smsUserService;

    public List<Integer> queryUserIdsFor(Integer userId) {
        List<Integer> finalUserIdList = new ArrayList<>();
        fetchUserId(queryUserIdsByParentUserId(userId), userId, finalUserIdList);
        return finalUserIdList;
    }

    public SmsUser getSmsUser(String username, String password) {
        return smsUserService.queryUserInfoFor(username, password);
    }

    @NotNull
    private List<Integer> queryUserIdsByParentUserId(Integer userId) {
        return smsUserService.queryUserInfoListByParentUserId(userId)
                .stream()
                .map(SmsUser::getUserId)
                .collect(Collectors.toList());
    }

    private void fetchUserId(List<Integer> userIdList, Integer userId, List<Integer> result) {

        if (CollectionUtils.isEmpty(userIdList)) {
            result.add(userId);
        } else {
            result.add(userId);
            for (Integer subVal : userIdList) {
                fetchUserId(queryUserIdsByParentUserId(subVal), subVal, result);
            }
        }
    }
}
